package com.sdp.right.control;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sdp.core.bizc.db.Query;
import com.sdp.core.bizc.utils.UniqueCheckTools;
import com.sdp.core.bizc.vo.DataCenter;
import com.sdp.core.bizc.vo.Result;
import com.sdp.right.cron.TaskCollection;
import com.sdp.right.db.sys_cron.service.ISysCronService;
import com.sdp.right.entity.SysCron;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zsp
 * @since 2023-10-18
 */
@RestController
@RequestMapping("/SysCronController")
public class SysCronController {
	
	@Autowired
	private ISysCronService iSysCronService;
	
	@Autowired
	private Query query;
	
	@Autowired
	private UniqueCheckTools uniqueCheckTools;
	
	@PostMapping(value = "/page")
	public Result<?> page(@RequestBody DataCenter dataCenter) {
		return Result.ok(query.page(iSysCronService, SysCron.class, dataCenter));
	}
	
	
	@PostMapping(value = "/save")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> save(@RequestBody SysCron cron) {
		if(cron==null) {
			return Result.error("任务信息为空");
		}
		if(StringUtils.isEmpty(cron.getKeyId())) {
			Result<?> r = uniqueCheckTools.isUniqueSingle(iSysCronService, SysCron.class, new String[] {"taskClass"}, "keyId", cron, null, false);
			if(r==null || !r.isSuccess()) {
				return Result.error("任务实现类不能重复");
			}
			
			//任务保存到数据库
			iSysCronService.save(cron);
		}else {
			Result<?> r = uniqueCheckTools.isUniqueSingle(iSysCronService, SysCron.class, new String[] {"taskClass"}, "keyId", null, cron, false);
			if(r==null || !r.isSuccess()) {
				return Result.error("任务实现类不能重复");
			}
			iSysCronService.updateById(cron);
		}
		TaskCollection.addTask(cron.getTaskClass(), cron);
		return Result.ok();
	}
	
}

